package configuracoes;

import java.awt.Dimension;

import javax.media.Format;
import javax.media.control.FormatControl;
import javax.media.format.RGBFormat;
import javax.media.format.VideoFormat;
import javax.media.protocol.CaptureDevice;
import javax.media.protocol.DataSource;

public class WebcamFormat {

	private DataSource datasource;

	public WebcamFormat(DataSource datasource) {
		super();
		this.datasource = datasource;
	}

	public void configure(Dimension size) {
		FormatControl[] formatControls = ((CaptureDevice) datasource).getFormatControls();
		
		for (int i = 0; i < formatControls.length; i++) {
			FormatControl fc = formatControls[i];
			Format[] formats = fc.getSupportedFormats();
			
			for (int j = 0; j < formats.length; j++) {
				if (matchProperties(formats[j], size)) {
					fc.setFormat(formats[j]);
					break;
				}
			}
		}
	}
	
	private boolean matchProperties(Format format, Dimension size){	
		VideoFormat videoFormat = (VideoFormat)format;
		if(!matchDimension(videoFormat, size)){
			return false;
		}
		
		return true;
	}
	
	private boolean matchDimension(VideoFormat format, Dimension size) {
		return format.getSize().equals(size);		
	}

	@SuppressWarnings("unused")
	private boolean matchVideoFormat(Format format){
		return format instanceof RGBFormat;
	}

}
